package main

import (
	"fmt"
	"sync"
	"time"
)

// atomic原子性，并发安全
// go提供了原子化的操作
type atomicInt struct {
	value int
	lock  sync.Mutex //互斥量
}

func (a *atomicInt) increment() {
	fmt.Println("safe increment")
	func() {
		a.lock.Lock()         //加锁
		defer a.lock.Unlock() //锁释放，正确写法

		a.value++
	}()
}

func (a *atomicInt) get() int {
	a.lock.Lock()
	defer a.lock.Unlock()

	return a.value
}

// 通过race查看数据冲突
// go run -race atomic.go
func main() {
	var a atomicInt
	a.increment()
	go func() {
		a.increment()
	}()
	time.Sleep(time.Millisecond)
	fmt.Println(a.get())
}
